/**
 * 
 */
package gopi.labs.database;

import gopi.labs.Connector.NameValue;
import gopi.labs.exceptions.InvalidDataRecord;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author GS4
 * 
 */
public abstract class CloudSpace extends Database {

	public abstract void create() throws SQLException, InvalidDataRecord;

	public abstract void update() throws SQLException, InvalidDataRecord;

	public abstract void drop() throws SQLException;

	public CloudSpace(String name) {
		super(name);

	}

	
	@Override
	public List<NameValue> getAttributeDetails() throws SQLException,
			InvalidDataRecord {

		List<NameValue> cloudDetails = new ArrayList<NameValue>();
		Statement stmt = this.connection.createStatement();
		if (!checkCloudExists(this.getName()))
			throw new InvalidDataRecord("Cloud name " + this.getName()
					+ " does not exist");

		ResultSet rs = stmt
				.executeQuery("select * from metadata.cloud where name = '"
						+ this.getName() + "'");

		while (rs.next()) {
			for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
				cloudDetails.add(new NameValue(rs.getMetaData().getColumnLabel(
						i), rs.getString(i)));
			}
		}
		rs = stmt
				.executeQuery("select * from metadata.cloud_attributes where name = '"
						+ this.getName() + "'");

		while (rs.next()) {
			cloudDetails.add(new NameValue(rs.getString("attribute"), rs
					.getString("value")));
		}
		return cloudDetails;

	}

	@Override
	public void insertUpdateAttributes(List<NameValue> attributes) throws SQLException {

		Statement stmt = this.connection.createStatement();
		for (int i = 0; i < attributes.size(); i++) {
			ResultSet rs = stmt.executeQuery("select count(*) from metadata.cloud_attributes where name = '" + this.getName()
					+ "' and attribute='"
					+ attributes.get(i).getName().toString() + "'");
			rs.next();
			if (rs.getInt(1) == 0) {
				stmt.execute("insert into metadata.cloud_attributes"
						+ " (name, attribute, value) values " + "('"
						+ this.getName() + "','" + attributes.get(i).getName()
						+ "','" + attributes.get(i).getValue() + "')");
			} else {
				stmt.execute("update metadata.cloud_attributes  set value =  '"
						+ attributes.get(i).getValue() + "' where name = '"
						+ this.getName() + "' and attribute = '"
						+ attributes.get(i).getName() + "'");
			}
			rs.close();
		}
	}
}
